package com.jalonjia.seckill.core.controller;

import com.jalonjia.seckill.common.core.constant.CacheConstants;
import com.jalonjia.seckill.common.core.util.R;
import com.jalonjia.seckill.common.log.annotation.SysLog;
import com.jalonjia.seckill.common.security.util.SecurityUtils;
import com.jalonjia.seckill.core.entity.SeckillOrder;
import com.jalonjia.seckill.core.service.SeckillOrderService;
import com.jalonjia.seckill.core.service.SeckillService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * 秒杀
 *
 * @author 贾晓超
 * @date 2022-05-05 20:56:44
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/seckill")
@Tag(name = "秒杀")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class SeckillController {
	private final SeckillService seckillService;
	private final SeckillOrderService seckillOrderService;
	private final AmqpTemplate amqpTemplate;

	/**
	 * 秒杀详情
	 *
	 * @param activityNo 秒杀活动编号
	 * @return
	 */
	@Operation(summary = "秒杀详情", description = "秒杀详情")
	@GetMapping("/detail/{activityNo}")
	@PreAuthorize("@pms.hasPermission('core_seckilltarget_get')")
	@Cacheable(value = CacheConstants.SECKILL_DETAIL, key = "#activityNo + '_detail'")
	public R getSeckillTargetPage(@PathVariable("activityNo") Long activityNo) {
		return R.ok(seckillService.getActivityDetailByNo(activityNo));
	}

	/**
	 * 是否参与过秒杀
	 *
	 * @param activityNo 秒杀活动编号
	 * @return
	 */
	@Operation(summary = "是否参与过秒杀", description = "是否参与过秒杀")
	@GetMapping("/did/{activityNo}")
	@PreAuthorize("@pms.hasPermission('core_seckilltarget_get')")
	public R didSeckillByActivityNo(@PathVariable("activityNo") Long activityNo) {
		return R.ok(seckillOrderService.haveOrderByActivityNo(activityNo, SecurityUtils.username()));
	}

	/**
	 * 秒杀提单
	 *
	 * @param seckillOrder 秒杀订单
	 * @return
	 */
	@SysLog("秒杀提单")
	@Operation(summary = "秒杀提单", description = "秒杀提单")
	@PostMapping("/submit")
	@PreAuthorize("@pms.hasPermission('core_seckilltarget_get')")
	@CacheEvict(value = CacheConstants.SECKILL_DETAIL, allEntries = true)
	public R getSeckillTargetPage(@RequestBody SeckillOrder seckillOrder) {
		return seckillService.submitOrder(seckillOrder);
	}
}
